﻿using Microsoft.Practices.ServiceLocation;
using MyToolkit.Multimedia;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Youtube_HD.Model;
using Youtube_HD.Services;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace Youtube_HD.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class PlayItems : Page
    {
        SystemMediaTransportControls systemMediaControls = null;
        PlayerItem playItem = null;
        public PlayItems()
        {
            this.InitializeComponent();
            this.Loaded += PlayItems_Loaded;
        }
        private IHomeViewModel homeViewModel
        {
            get { return ServiceLocator.Current.GetInstance<IHomeViewModel>(); }
        }
        async void PlayItems_Loaded(object sender, RoutedEventArgs e)
        {
            LoadData.IsActive = true;
            YouTubeUri getVideos = await homeViewModel.GetVideoUriAsync(playItem.id, MyToolkit.Multimedia.YouTubeQuality.QualityMedium);
            Scenario2MediaElement.Source = getVideos.Uri;
            Scenario2MediaElement.MediaOpened += Scenario2MediaElement_MediaOpened;
          
        }

        void Scenario2MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            LoadData.IsActive = false;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            playItem = (PlayerItem)e.Parameter;
            // PlayTo handling requires either no support for SystemMediaTransportControls or
            // support for Play and Pause similar to background audio.  If the SystemMediaTransportControls
            // have been initialized in another scenario than we also need to hook them up here or PlayTo
            // will fail.
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;

            Scenario2MediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
        }

        /// <summary>
        /// Invoked when this page is about to be removed from a Frame.
        /// </summary>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (systemMediaControls != null)
            {
                systemMediaControls.ButtonPressed -= SystemMediaControls_ButtonPressed;
                systemMediaControls.IsPlayEnabled = false;
                systemMediaControls.IsPauseEnabled = false;
                systemMediaControls.IsStopEnabled = false;
                systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
                systemMediaControls.DisplayUpdater.ClearAll();
                systemMediaControls.DisplayUpdater.Update();
                systemMediaControls = null;
            }

            // Set source to null to ensure it stops playing to a Play To device if applicable.
            Scenario2MediaElement.Source = null;
        }
        /// <summary>
        /// Handler for the system transport controls button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario2MediaElement.Play();
                    });
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario2MediaElement.Pause();
                    });
                    break;

                case SystemMediaTransportControlsButton.Stop:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario2MediaElement.Stop();
                    });
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// Handler for the media element state change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            SystemMediaTransportControls systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            switch (Scenario2MediaElement.CurrentState)
            {
                default:
                case MediaElementState.Closed:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
                    break;

                case MediaElementState.Opening:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Changing;
                    break;

                case MediaElementState.Buffering:
                case MediaElementState.Playing:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Playing;
                    break;

                case MediaElementState.Paused:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Paused;
                    break;

                case MediaElementState.Stopped:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
                    break;
            }
        }
    }
}
